package com.xx.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@Controller
public class MyController {
    @RequestMapping("/upload")
    public String upload(List<MultipartFile> fileList, HttpServletRequest request) {
        System.out.println(11);
        if (!fileList.isEmpty()) {
            System.out.println(22);
            for (MultipartFile multipartFile : fileList) {
                String originalFilename = multipartFile.getOriginalFilename();
                File dir = new File("D:/fileUpload/");
                if (!dir.exists()) {
                    boolean isMkdir = dir.mkdirs();
                    System.out.println(isMkdir);
                }
                String newFileName = UUID.randomUUID() + "__" + originalFilename;

                try {
                    multipartFile.transferTo(new File("D:/fileUpload/" + newFileName));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/index.jsp";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String filename) throws IOException {
        File file = new File("D:/fileUpload/" + filename);

        System.out.println(file.exists());

        HttpHeaders headers = new HttpHeaders();

        // 通知浏览器以下载方式打开文件，顺便解决中文乱码问题
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, "UTF-8"));

        // 以流的方式返回数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }
}
